package com.sinogrand.elevator.ui.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.ExitToApp
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.pulltorefresh.PullToRefreshContainer
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.zIndex
import kotlinx.coroutines.delay
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.layout.ContentScale
import coil.compose.AsyncImage
import com.sinogrand.elevator.ui.components.LogItem
import com.sinogrand.elevator.data.models.ElevatorDetailInfo
import com.sinogrand.elevator.data.models.ElevatorLogItem
import com.sinogrand.elevator.data.models.ElevatorLogListResponse
import com.sinogrand.elevator.repository.ElevatorRepository
import android.util.Log
import com.sinogrand.elevator.utils.Constants
import com.sinogrand.elevator.utils.LogTags
import com.sinogrand.elevator.utils.StringUtils
import com.sinogrand.elevator.utils.TokenManager

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ElevatorDetailScreen(
    elevatorId: Int,
    onBackClick: () -> Unit,
    onNavigateToApproval: (formId: Int, elevatorId: Int, projectId: Int) -> Unit,
    onNavigateToApprovalWithTemplate: (templateId: Int, elevatorId: Int, projectId: Int) -> Unit
) {
    // 输出接收到的参数
    Log.d(LogTags.ELEVATOR_DETAIL, "📱 ElevatorDetailScreen 接收参数 - elevatorId: $elevatorId")
    Log.d(LogTags.ELEVATOR_DETAIL, "📱 ElevatorDetailScreen 新增回调 - onNavigateToApprovalWithTemplate 已设置")
    
    val context = LocalContext.current
    val elevatorRepository = remember { ElevatorRepository(context) }
    val tokenManager = remember { TokenManager(context) }
    
    var elevatorDetail by remember { mutableStateOf<ElevatorDetailInfo?>(null) }
    var isLoading by remember { mutableStateOf(true) }
    var errorMessage by remember { mutableStateOf<String?>(null) }
    var selectedTab by rememberSaveable { mutableIntStateOf(0) }
    
    // 输出电梯详情对象和模版列表
    LaunchedEffect(elevatorDetail) {
        if (elevatorDetail != null) {
            val userInfo = tokenManager.getUserInfo()
            Log.d(LogTags.ELEVATOR_DETAIL, "📱 电梯详情页面 - 电梯详情对象:")
            Log.d(LogTags.ELEVATOR_DETAIL, StringUtils.formatString(elevatorDetail.toString()))
            Log.d(LogTags.ELEVATOR_DETAIL, "📱 电梯详情页面 - 用户模版列表:")
            Log.d(LogTags.ELEVATOR_DETAIL, StringUtils.formatString(userInfo?.template_list?.toString() ?: "无数据"))
        }
    }
    
    val tabs = listOf("信息", "日志", "巡视", "超期")
    
    // 计算显示的标题
    val displayTitle = when {
        isLoading -> "" // 加载中不显示标题
        elevatorDetail != null -> {
            val elevatorNo = elevatorDetail!!.no
            val statusText = Constants.ElevatorStatus.getStatusDescription(elevatorDetail!!.status)
            "$elevatorNo - $statusText"
        }
        else -> "" // 加载失败也不显示标题
    }
    
    // 获取电梯详情数据
    LaunchedEffect(elevatorId) {
        isLoading = true
        errorMessage = null
        
        elevatorRepository.getElevatorDetail(elevatorId)
            .onSuccess { data ->
                elevatorDetail = data.info
                isLoading = false
            }
            .onFailure { exception ->
                errorMessage = exception.message
                isLoading = false
            }
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        text = displayTitle,
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFF1F2937)
                    )
                },
                navigationIcon = {
                    IconButton(onClick = onBackClick) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "返回",
                            tint = Color(0xFF374151)
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color.White,
                    titleContentColor = Color(0xFF1F2937)
                ),
                modifier = Modifier.shadow(2.dp)
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(
                    Brush.verticalGradient(
                        colors = listOf(
                            Color(0xFFF8FAFC),
                            Color(0xFFF1F5F9)
                        )
                    )
                )
                .padding(paddingValues)
        ) {
        
        // Tab选择器
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(start = 16.dp, top = 16.dp, end = 16.dp, bottom = 8.dp),
            colors = CardDefaults.cardColors(
                containerColor = Color.White
            ),
            elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
            shape = RoundedCornerShape(12.dp)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(4.dp),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                tabs.forEachIndexed { index, tabTitle ->
                    TabButton(
                        text = tabTitle,
                        isSelected = selectedTab == index,
                        onClick = { selectedTab = index },
                        modifier = Modifier.weight(1f)
                    )
                }
            }
        }
        
        // Tab内容区域
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
        ) {
            when {
                isLoading -> {
                    // 加载状态
                    Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator(
                            color = Color(0xFF3B82F6)
                        )
                    }
                }
                errorMessage != null -> {
                    // 错误状态
                    Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center
                    ) {
                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Icon(
                                imageVector = Icons.Default.Error,
                                contentDescription = null,
                                tint = Color(0xFFEF4444),
                                modifier = Modifier.size(64.dp)
                            )
                            Spacer(modifier = Modifier.height(16.dp))
                            Text(
                                text = "加载失败",
                                fontSize = 16.sp,
                                color = Color(0xFF6B7280),
                                fontWeight = FontWeight.Medium
                            )
                            Spacer(modifier = Modifier.height(8.dp))
                            Text(
                                text = errorMessage ?: "未知错误",
                                fontSize = 14.sp,
                                color = Color(0xFF9CA3AF)
                            )
                        }
                    }
                }
                elevatorDetail != null -> {
                    when (selectedTab) {
                        0 -> ElevatorInfoTab(
                            elevatorDetail = elevatorDetail!!,
                            onRefresh = {
                                elevatorRepository.getElevatorDetail(elevatorId)
                                    .onSuccess { data ->
                                        elevatorDetail = data.info
                                    }
                                    .onFailure { exception ->
                                        errorMessage = exception.message
                                    }
                            }
                        )
                        1 -> ElevatorInstallationLogsTab(
                            elevatorId = elevatorId, 
                            projectId = elevatorDetail!!.project_id,
                            onNavigateToApproval = onNavigateToApproval
                        )
                        2 -> ElevatorSafetyInspectionTab(
                            elevatorId = elevatorId, 
                            projectId = elevatorDetail!!.project_id,
                            onNavigateToApproval = onNavigateToApproval
                        )
                        3 -> ElevatorOverdueExplanationTab(
                            elevatorId = elevatorId, 
                            projectId = elevatorDetail!!.project_id,
                            onNavigateToApproval = onNavigateToApproval
                        )
                    }
                }
            }
        }
        
        // 底部公共工具栏
        ElevatorDetailToolbar(
            elevatorDetail = elevatorDetail,
            onNavigateToApproval = onNavigateToApproval,
            onNavigateToApprovalWithTemplate = onNavigateToApprovalWithTemplate
        )
        }
    }
}


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ElevatorInfoTab(
    elevatorDetail: ElevatorDetailInfo,
    onRefresh: suspend () -> Unit
) {
    var isRefreshing by rememberSaveable { mutableStateOf(false) }
    val pullRefreshState = rememberPullToRefreshState()
    
    // 下拉刷新
    if (pullRefreshState.isRefreshing) {
        LaunchedEffect(true) {
            isRefreshing = true
            try {
                onRefresh() // 调用真正的刷新逻辑
            } catch (e: Exception) {
                Log.e(LogTags.ELEVATOR_DETAIL, "刷新电梯详情失败: ${e.message}")
            } finally {
                isRefreshing = false
                pullRefreshState.endRefresh()
            }
        }
    }
    
    Box(
        modifier = Modifier
            .fillMaxSize()
            .nestedScroll(pullRefreshState.nestedScrollConnection)
    ) {
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(horizontal = 16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp),
            contentPadding = PaddingValues(
                top = 8.dp,
                bottom = 16.dp
            )
        ) {
            item {
                // 电梯信息卡片
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(
                        containerColor = Color.White
                    ),
                    elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
                    shape = RoundedCornerShape(12.dp)
                ) {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp)
                    ) {
                        Text(
                            text = "电梯信息",
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Bold,
                            color = Color(0xFF1F2937)
                        )
                        
                        Spacer(modifier = Modifier.height(12.dp))
                        
                        // 使用details列表展示所有信息
                        elevatorDetail.details.forEachIndexed { index, detail ->
                            InfoRow(detail.name, detail.value)
                            if (index < elevatorDetail.details.size - 1) {
                                HorizontalDivider(
                                    modifier = Modifier.padding(vertical = 8.dp),
                                    color = Color(0xFFE5E7EB),
                                    thickness = 0.5.dp
                                )
                            }
                        }
                    }
                }
            }
            
            // 产品配置表
            if (elevatorDetail.product_config_table.isNotEmpty()) {
                item {
                    Card(
                        modifier = Modifier.fillMaxWidth(),
                        colors = CardDefaults.cardColors(
                            containerColor = Color.White
                        ),
                        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
                        shape = RoundedCornerShape(12.dp)
                    ) {
                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp)
                        ) {
                            Text(
                                text = "产品配置表",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Bold,
                                color = Color(0xFF1F2937)
                            )
                            
                            Spacer(modifier = Modifier.height(12.dp))
                            
                            // 图片列表
                            Column(
                                verticalArrangement = Arrangement.spacedBy(8.dp)
                            ) {
                                elevatorDetail.product_config_table.forEach { imageUrl ->
                                    AsyncImage(
                                        model = imageUrl,
                                        contentDescription = "产品配置图",
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .heightIn(min = 200.dp),
                                        contentScale = ContentScale.Fit
                                    )
                                }
                            }
                        }
                    }
                }
            } else {
                // 测试用的产品配置表
                item {
                    Card(
                        modifier = Modifier.fillMaxWidth(),
                        colors = CardDefaults.cardColors(
                            containerColor = Color.White
                        ),
                        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
                        shape = RoundedCornerShape(12.dp)
                    ) {
                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp)
                        ) {
                            Text(
                                text = "产品配置表",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Bold,
                                color = Color(0xFF1F2937)
                            )
                            
                            Spacer(modifier = Modifier.height(12.dp))
                            
                            // 测试图片列表
                            val testImages = listOf(
                                "https://inews.gtimg.com/om_bt/OQOV4kCeeM-pxfRVxp-akL5OeNX3X6meNp3cC93zl1YrcAA/1000",
                                "https://img-nos.yiyouliao.com/alph/39b516d9aa2a656806f71c77e9d3427b.jpeg?yiyouliao_channel=vivo_image"
                            )
                            
                            Column(
                                verticalArrangement = Arrangement.spacedBy(8.dp)
                            ) {
                                testImages.forEach { imageUrl ->
                                    AsyncImage(
                                        model = imageUrl,
                                        contentDescription = "产品配置图",
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .heightIn(min = 200.dp),
                                        contentScale = ContentScale.Fit
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }
        
        // 下拉刷新容器
        if (pullRefreshState.isRefreshing || pullRefreshState.progress > 0f) {
            PullToRefreshContainer(
                state = pullRefreshState,
                modifier = Modifier
                    .align(Alignment.TopCenter)
                    .zIndex(1f)
            )
        }
    }
}

@Composable
fun InfoRow(label: String, value: String) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 6.dp),
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Text(
            text = label,
            fontSize = 14.sp,
            color = Color(0xFF6B7280),
            modifier = Modifier.weight(1f)
        )
        
        Text(
            text = value,
            fontSize = 14.sp,
            color = Color(0xFF1F2937),
            fontWeight = FontWeight.Medium,
            modifier = Modifier.weight(1f)
        )
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ElevatorInstallationLogsTab(
    elevatorId: Int,
    projectId: Int,
    onNavigateToApproval: (formId: Int, elevatorId: Int, projectId: Int) -> Unit
) {
    // 输出接收到的参数
    Log.d(LogTags.ELEVATOR_DETAIL, "📋 ElevatorInstallationLogsTab 接收参数 - elevatorId: $elevatorId")
    
    val context = LocalContext.current
    val elevatorRepository = remember { ElevatorRepository(context) }
    
    var isRefreshing by rememberSaveable { mutableStateOf(false) }
    var isLoadingMore by rememberSaveable { mutableStateOf(false) }
    var canLoadMore by rememberSaveable { mutableStateOf(true) }
    var currentPage by rememberSaveable { mutableIntStateOf(1) }
    var isLoading by rememberSaveable { mutableStateOf(true) }
    var errorMessage by rememberSaveable { mutableStateOf<String?>(null) }
    
    val pullRefreshState = rememberPullToRefreshState()
    val listState = rememberLazyListState()
    
    // 真实日志数据
    var logs by rememberSaveable { mutableStateOf<List<ElevatorLogItem>>(emptyList()) }
    
    // 初始化数据
    LaunchedEffect(elevatorId) {
        isLoading = true
        errorMessage = null
        
        elevatorRepository.getElevatorLogList(elevatorId, 1, 1, 20)
            .onSuccess { response: ElevatorLogListResponse ->
                logs = response.list
                canLoadMore = response.page_info.page < (response.page_info.total / response.page_info.size + 1)
                isLoading = false
            }
            .onFailure { exception ->
                errorMessage = exception.message
                isLoading = false
            }
    }
    
    // 下拉刷新
    if (pullRefreshState.isRefreshing) {
        LaunchedEffect(true) {
            isRefreshing = true
            elevatorRepository.getElevatorLogList(elevatorId, 1, 1, 20)
                .onSuccess { response: ElevatorLogListResponse ->
                    logs = response.list
                    currentPage = 1
                    canLoadMore = response.page_info.page < (response.page_info.total / response.page_info.size + 1)
                }
                .onFailure { exception ->
                    errorMessage = exception.message
                }
            isRefreshing = false
            pullRefreshState.endRefresh()
        }
    }
    
    // 上拉加载更多
    LaunchedEffect(listState) {
        snapshotFlow { listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index }
            .collect { lastVisibleIndex ->
                if (lastVisibleIndex != null && 
                    lastVisibleIndex >= logs.size - 1 && 
                    canLoadMore && 
                    !isLoadingMore &&
                    logs.isNotEmpty()) { // 确保列表不为空
                    isLoadingMore = true
                    elevatorRepository.getElevatorLogList(elevatorId, 1, currentPage + 1, 20)
                        .onSuccess { response: ElevatorLogListResponse ->
                            logs = logs + response.list
                        currentPage++
                            canLoadMore = response.page_info.page < (response.page_info.total / response.page_info.size + 1)
                        }
                        .onFailure { exception ->
                            errorMessage = exception.message
                    }
                    isLoadingMore = false
                }
            }
    }
    
        Box(
            modifier = Modifier
            .fillMaxSize()
                .nestedScroll(pullRefreshState.nestedScrollConnection)
        ) {
        when {
            isLoading -> {
                // 加载状态
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator(
                        color = Color(0xFF3B82F6)
                    )
                }
            }
            errorMessage != null -> {
                // 错误状态
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Icon(
                            imageVector = Icons.Default.Error,
                            contentDescription = null,
                            tint = Color(0xFFEF4444),
                            modifier = Modifier.size(64.dp)
                        )
                        
                        Spacer(modifier = Modifier.height(16.dp))
                        
                        Text(
                            text = "加载失败",
                            fontSize = 16.sp,
                            color = Color(0xFF6B7280),
                            fontWeight = FontWeight.Medium
                        )
                        
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        Text(
                            text = errorMessage ?: "未知错误",
                            fontSize = 14.sp,
                            color = Color(0xFF9CA3AF)
                        )
                    }
                }
            }
            logs.isEmpty() -> {
                // 空状态 - 使用LazyColumn确保有足够高度触发下拉刷新
                LazyColumn(
                    modifier = Modifier.fillMaxSize(),
                    contentPadding = PaddingValues(16.dp),
                    verticalArrangement = Arrangement.Center
                ) {
                    item {
                        Column(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Icon(
                                imageVector = Icons.Default.Description,
                                contentDescription = null,
                                tint = Color(0xFF9CA3AF),
                                modifier = Modifier.size(64.dp)
                            )
                            
                            Spacer(modifier = Modifier.height(16.dp))
                            
                            Text(
                                text = "暂无安装日志记录",
                                fontSize = 16.sp,
                                color = Color(0xFF6B7280),
                                fontWeight = FontWeight.Medium
                            )
                            
                            Spacer(modifier = Modifier.height(8.dp))
                            
                            Text(
                                text = "下拉刷新获取最新数据",
                                fontSize = 14.sp,
                                color = Color(0xFF9CA3AF)
                            )
                        }
                    }
                }
            }
            else -> {
                // 日志列表
                LazyColumn(
                    state = listState,
                    modifier = Modifier.fillMaxSize(),
                    contentPadding = PaddingValues(16.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    items(logs.size) { index ->
                        val log = logs[index]
                        ElevatorLogItemCard(
                            log = log,
                            onClick = { 
                                Log.d(LogTags.ELEVATOR_DETAIL, "📋 安装日志点击 - formId: ${log.form_id}, elevatorId: $elevatorId, projectId: $projectId")
                                onNavigateToApproval(log.form_id, elevatorId, projectId) 
                            }
                        )
                    }
                    
                    // 加载更多指示器
                    if (isLoadingMore) {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(24.dp),
                                    color = Color(0xFF3B82F6),
                                    strokeWidth = 2.dp
                                )
                            }
                            }
                        }
                    }
                }
            }
            
            // 下拉刷新容器
            if (pullRefreshState.isRefreshing || pullRefreshState.progress > 0f) {
                PullToRefreshContainer(
                    state = pullRefreshState,
                    modifier = Modifier
                        .align(Alignment.TopCenter)
                        .zIndex(1f)
                )
        }
    }
}

@Composable
fun BottomActionButton(
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    title: String,
    enabled: Boolean = true,
    onClick: () -> Unit
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier.clickable(enabled = enabled) { onClick() }
    ) {
        Card(
            modifier = Modifier.size(48.dp),
            colors = CardDefaults.cardColors(
                containerColor = if (enabled) Color(0xFFF3F4F6) else Color(0xFFE5E7EB)
            ),
            elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
            shape = RoundedCornerShape(8.dp)
        ) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    imageVector = icon,
                    contentDescription = null,
                    tint = if (enabled) Color(0xFF3B82F6) else Color(0xFF9CA3AF),
                    modifier = Modifier.size(24.dp)
                )
            }
        }
        
        Spacer(modifier = Modifier.height(8.dp))
        
        Text(
            text = title,
            fontSize = 12.sp,
            color = if (enabled) Color(0xFF1F2937) else Color(0xFF9CA3AF),
            fontWeight = FontWeight.Medium
        )
    }
}

// 模拟日志数据
fun getMockLogs(page: Int = 1): List<LogItem> {
    return if (page == 1) {
        listOf(
            LogItem(1, "电梯安装开始", "开始安装电梯设备", "安装", "2025-01-15 09:00:00", 1),
            LogItem(2, "安全检查", "进行安全巡视检查", "安全", "2025-01-15 14:30:00", 1),
            LogItem(3, "设备调试", "完成设备调试工作", "调试", "2025-01-16 10:15:00", 1),
            LogItem(4, "质量验收", "通过质量验收检查", "验收", "2025-01-16 16:45:00", 1),
            LogItem(5, "安装完成", "电梯安装工作完成", "安装", "2025-01-17 11:20:00", 1)
        )
    } else {
        emptyList() // 模拟没有更多数据
    }
}

@Composable
fun ElevatorLogItemCard(
    log: ElevatorLogItem,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onClick() },
        colors = CardDefaults.cardColors(
            containerColor = Color.White
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 1.dp),
        shape = RoundedCornerShape(8.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = log.user_name.ifEmpty { "未知用户" },
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Medium,
                    color = Color(0xFF1F2937)
                )
                
                Text(
                    text = log.created_at,
                    fontSize = 12.sp,
                    color = Color(0xFF9CA3AF)
                )
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            Text(
                text = log.content,
                fontSize = 14.sp,
                color = Color(0xFF6B7280),
                lineHeight = 20.sp
            )
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ElevatorSafetyInspectionTab(
    elevatorId: Int,
    projectId: Int,
    onNavigateToApproval: (formId: Int, elevatorId: Int, projectId: Int) -> Unit
) {
    // 输出接收到的参数
    Log.d(LogTags.ELEVATOR_DETAIL, "🔍 ElevatorSafetyInspectionTab 接收参数 - elevatorId: $elevatorId")
    
    val context = LocalContext.current
    val elevatorRepository = remember { ElevatorRepository(context) }
    
    var isRefreshing by rememberSaveable { mutableStateOf(false) }
    var isLoadingMore by rememberSaveable { mutableStateOf(false) }
    var canLoadMore by rememberSaveable { mutableStateOf(true) }
    var currentPage by rememberSaveable { mutableIntStateOf(1) }
    var isLoading by rememberSaveable { mutableStateOf(true) }
    var errorMessage by rememberSaveable { mutableStateOf<String?>(null) }
    
    val pullRefreshState = rememberPullToRefreshState()
    val listState = rememberLazyListState()
    
    // 真实安全巡视数据
    var inspections by rememberSaveable { mutableStateOf<List<ElevatorLogItem>>(emptyList()) }
    
    // 初始化数据
    LaunchedEffect(elevatorId) {
        isLoading = true
        errorMessage = null
        
        elevatorRepository.getElevatorLogList(elevatorId, 2, 1, 20)
            .onSuccess { response: ElevatorLogListResponse ->
                inspections = response.list
                canLoadMore = response.page_info.page < (response.page_info.total / response.page_info.size + 1)
                isLoading = false
            }
            .onFailure { exception ->
                errorMessage = exception.message
                isLoading = false
            }
    }
    
    // 下拉刷新
    if (pullRefreshState.isRefreshing) {
        LaunchedEffect(true) {
            isRefreshing = true
            elevatorRepository.getElevatorLogList(elevatorId, 2, 1, 20)
                .onSuccess { response: ElevatorLogListResponse ->
                    inspections = response.list
                    currentPage = 1
                    canLoadMore = response.page_info.page < (response.page_info.total / response.page_info.size + 1)
                }
                .onFailure { exception ->
                    errorMessage = exception.message
                }
            isRefreshing = false
            pullRefreshState.endRefresh()
        }
    }
    
    // 上拉加载更多
    LaunchedEffect(listState) {
        snapshotFlow { listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index }
            .collect { lastVisibleIndex ->
                if (lastVisibleIndex != null && 
                    lastVisibleIndex >= inspections.size - 1 && 
                    canLoadMore && 
                    !isLoadingMore &&
                    inspections.isNotEmpty()) { // 确保列表不为空
                    isLoadingMore = true
                    elevatorRepository.getElevatorLogList(elevatorId, 2, currentPage + 1, 20)
                        .onSuccess { response: ElevatorLogListResponse ->
                            inspections = inspections + response.list
                            currentPage++
                            canLoadMore = response.page_info.page < (response.page_info.total / response.page_info.size + 1)
                        }
                        .onFailure { exception ->
                            errorMessage = exception.message
                        }
                    isLoadingMore = false
                }
            }
    }
    
    Box(
        modifier = Modifier
            .fillMaxSize()
            .nestedScroll(pullRefreshState.nestedScrollConnection)
    ) {
        when {
            isLoading -> {
                // 加载状态
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator(
                        color = Color(0xFF3B82F6)
                    )
                }
            }
            errorMessage != null -> {
                // 错误状态
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Icon(
                            imageVector = Icons.Default.Error,
                            contentDescription = null,
                            tint = Color(0xFFEF4444),
                            modifier = Modifier.size(64.dp)
                        )
                        
                        Spacer(modifier = Modifier.height(16.dp))
                        
                        Text(
                            text = "加载失败",
                            fontSize = 16.sp,
                            color = Color(0xFF6B7280),
                            fontWeight = FontWeight.Medium
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
                        Text(
                            text = errorMessage ?: "未知错误",
                            fontSize = 14.sp,
                            color = Color(0xFF9CA3AF)
                        )
                    }
                }
            }
            inspections.isEmpty() -> {
                // 空状态 - 使用LazyColumn确保有足够高度触发下拉刷新
                LazyColumn(
                    modifier = Modifier.fillMaxSize(),
                    contentPadding = PaddingValues(16.dp),
                    verticalArrangement = Arrangement.Center
                ) {
                    item {
                        Column(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Icon(
                                imageVector = Icons.Default.Security,
                                contentDescription = null,
                                tint = Color(0xFF9CA3AF),
                                modifier = Modifier.size(64.dp)
                            )
                            
                            Spacer(modifier = Modifier.height(16.dp))
                            
                            Text(
                                text = "暂无安全巡视记录",
                                fontSize = 16.sp,
                                color = Color(0xFF6B7280),
                                fontWeight = FontWeight.Medium
                            )
                            
                            Spacer(modifier = Modifier.height(8.dp))
                            
                            Text(
                                text = "下拉刷新获取最新数据",
                                fontSize = 14.sp,
                                color = Color(0xFF9CA3AF)
                            )
                        }
                    }
                }
            }
            else -> {
                // 安全巡视列表
                LazyColumn(
                    state = listState,
                    modifier = Modifier.fillMaxSize(),
                    contentPadding = PaddingValues(16.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    items(inspections.size) { index ->
                        val inspection = inspections[index]
                        ElevatorLogItemCard(
                            log = inspection,
                            onClick = { 
                                Log.d(LogTags.ELEVATOR_DETAIL, "🔍 安全巡视点击 - formId: ${inspection.form_id}, elevatorId: $elevatorId, projectId: $projectId")
                                onNavigateToApproval(inspection.form_id, elevatorId, projectId) 
                            }
                        )
                    }
                
                    // 加载更多指示器
                    if (isLoadingMore) {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(24.dp),
                                    color = Color(0xFF3B82F6),
                                    strokeWidth = 2.dp
                                )
                            }
                        }
                    }
                }
            }
        }
        
        // 下拉刷新容器
        if (pullRefreshState.isRefreshing || pullRefreshState.progress > 0f) {
            PullToRefreshContainer(
                state = pullRefreshState,
                modifier = Modifier
                    .align(Alignment.TopCenter)
                    .zIndex(1f)
            )
        }
    }
}

// 模拟安全巡视数据
fun getMockSafetyInspections(page: Int = 1): List<LogItem> {
    return if (page == 1) {
        listOf(
            LogItem(1, "日常安全巡视", "检查电梯运行状态，确认各项安全指标正常", "安全", "2025-01-15 09:00:00", 1),
            LogItem(2, "设备安全检查", "检查电梯门锁、按钮、指示灯等设备功能", "安全", "2025-01-15 14:30:00", 1),
            LogItem(3, "紧急制动测试", "测试电梯紧急制动系统，确保安全可靠", "安全", "2025-01-16 10:15:00", 1),
            LogItem(4, "消防联动检查", "检查电梯消防联动功能，确保符合消防要求", "安全", "2025-01-16 16:45:00", 1),
            LogItem(5, "定期维护检查", "进行电梯定期维护检查，更换磨损部件", "安全", "2025-01-17 11:20:00", 1)
        )
    } else {
        emptyList() // 模拟没有更多数据
    }
}

@Composable
fun SafetyInspectionCard(inspection: LogItem) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color.White
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 1.dp),
        shape = RoundedCornerShape(8.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = inspection.title,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Medium,
                    color = Color(0xFF1F2937)
                )
                
                Text(
                    text = inspection.created_at,
                    fontSize = 12.sp,
                    color = Color(0xFF9CA3AF)
                )
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            Text(
                text = inspection.content,
                fontSize = 14.sp,
                color = Color(0xFF6B7280),
                lineHeight = 20.sp
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Card(
                    colors = CardDefaults.cardColors(
                        containerColor = Color(0xFFFEF2F2) // 安全巡视使用红色主题
                    ),
                    elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
                    shape = RoundedCornerShape(4.dp)
                ) {
                    Text(
                        text = inspection.type,
                        fontSize = 12.sp,
                        color = Color(0xFFEF4444), // 红色文字
                        modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)
                    )
                }
            }
        }
    }
}

/**
 * 判断电梯详情是否有任何可显示的按钮
 * @param elevatorDetail 电梯详情信息
 * @return 是否有按钮需要显示
 */
private fun hasAnyButtons(elevatorDetail: ElevatorDetailInfo): Boolean {
    return when {
        // 如果电梯状态在待分配到移交之间，则显示电梯到货单和电梯开箱确认表按钮
        elevatorDetail.status >= Constants.ElevatorStatus.WAITING_ALLOCATION && 
        elevatorDetail.status < Constants.ElevatorStatus.TRANSFER -> true
        
        // 如果电梯状态为待开工，则显示电梯防护照片按钮
        elevatorDetail.status == Constants.ElevatorStatus.WAITING_START -> true
        
        // 如果电梯状态为放样中，则显示电梯放样照片按钮
        elevatorDetail.status == Constants.ElevatorStatus.SAMPLE_DRAWING -> true
        
        // 如果电梯状态为导轨厅门安装，则显示电梯导轨厅门安装按钮
        elevatorDetail.status == Constants.ElevatorStatus.TRACK_DOOR_INSTALLATION -> true
        
        // 如果电梯状态为快车调试，则显示电梯快车调试按钮
        elevatorDetail.status == Constants.ElevatorStatus.FAST_CAR_DEBUGGING -> true
        
        // 如果电梯状态为验收，则显示电梯验收按钮
        elevatorDetail.status == Constants.ElevatorStatus.ACCEPTANCE -> true
        
        // 如果电梯状态为慢车调试，则显示电梯慢车调试按钮
        elevatorDetail.status == Constants.ElevatorStatus.SLOW_CAR_DEBUGGING -> true
        
        else -> false
    }
}

@Composable
fun ElevatorDetailToolbar(
    elevatorDetail: ElevatorDetailInfo?,
    onNavigateToApproval: (formId: Int, elevatorId: Int, projectId: Int) -> Unit,
    onNavigateToApprovalWithTemplate: (templateId: Int, elevatorId: Int, projectId: Int) -> Unit
) {
    val context = LocalContext.current
    val tokenManager = remember { TokenManager(context) }
    val userInfo = tokenManager.getUserInfo()
    
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp),
        colors = CardDefaults.cardColors(
            containerColor = Color.White
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
        shape = RoundedCornerShape(12.dp)
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(108.dp) // 进一步增加高度以完整显示按钮文案
        ) {
            LazyRow(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp),
                horizontalArrangement = Arrangement.spacedBy(16.dp),
                contentPadding = PaddingValues(horizontal = 8.dp)
            ) {
                // 根据条件显示按钮
                if (elevatorDetail != null) {
                    
                    // 如果电梯状态在待分配到移交之间，则显示电梯到货单和电梯开箱确认表按钮
                    if (elevatorDetail.status >= Constants.ElevatorStatus.WAITING_ALLOCATION && 
                        elevatorDetail.status < Constants.ElevatorStatus.TRANSFER) {

                        // 电梯到货单按钮
                        item {
                            BottomActionButton(
                                icon = Icons.Default.LocalShipping,
                                title = "电梯到货单",
                                onClick = { 
                                    handleApprovalButtonClick(
                                        templateType = Constants.ApprovalTemplateType.ELEVATOR_ARRIVAL,
                                        elevatorDetail = elevatorDetail,
                                        userInfo = userInfo,
                                        onNavigateToApproval = onNavigateToApproval,
                                        onNavigateToApprovalWithTemplate = onNavigateToApprovalWithTemplate
                                    )
                                }
                            )
                        }
                        
                        // 电梯开箱确认表按钮
                        item {
                            BottomActionButton(
                                icon = Icons.Default.Inventory,
                                title = "电梯开箱确认表",
                                onClick = { 
                                    handleApprovalButtonClick(
                                        templateType = Constants.ApprovalTemplateType.ELEVATOR_UNPACKING,
                                        elevatorDetail = elevatorDetail,
                                        userInfo = userInfo,
                                        onNavigateToApproval = onNavigateToApproval,
                                        onNavigateToApprovalWithTemplate = onNavigateToApprovalWithTemplate
                                    )
                                }
                            )
                        }
                    }
                    
                    // 如果电梯状态为待开工，则显示电梯防护照片按钮
                    if (elevatorDetail.status == Constants.ElevatorStatus.WAITING_START) {
                        item {
                            BottomActionButton(
                                icon = Icons.Default.Shield,
                                title = "电梯防护照片",
                                enabled = elevatorDetail.check_inspection, // 根据check_inspection控制按钮状态
                                onClick = { 
                                    handleApprovalButtonClick(
                                        templateType = Constants.ApprovalTemplateType.ELEVATOR_PROTECTION,
                                        elevatorDetail = elevatorDetail,
                                        userInfo = userInfo,
                                        onNavigateToApproval = onNavigateToApproval,
                                        onNavigateToApprovalWithTemplate = onNavigateToApprovalWithTemplate
                                    )
                                }
                            )
                        }
                    }
                    
                    // 如果电梯状态为放样中，则显示电梯放样照片按钮
                    if (elevatorDetail.status == Constants.ElevatorStatus.SAMPLE_DRAWING) {
                        item {
                            BottomActionButton(
                                icon = Icons.Default.CameraAlt,
                                title = "电梯放样照片",
                                onClick = { 
                                    handleApprovalButtonClick(
                                        templateType = Constants.ApprovalTemplateType.ELEVATOR_LOFTING,
                                        elevatorDetail = elevatorDetail,
                                        userInfo = userInfo,
                                        onNavigateToApproval = onNavigateToApproval,
                                        onNavigateToApprovalWithTemplate = onNavigateToApprovalWithTemplate
                                    )
                                }
                            )
                        }
                    }
                    
                    // 放样打款按钮 - 在慢车调试到已归档状态之间都显示
                    if (elevatorDetail.status >= Constants.ElevatorStatus.SLOW_CAR_DEBUGGING && 
                        elevatorDetail.status <= Constants.ElevatorStatus.ARCHIVED) {
                        item {
                            BottomActionButton(
                                icon = Icons.Default.Payment,
                                title = "放样打款",
                                onClick = { 
                                    handleApprovalButtonClick(
                                        templateType = Constants.ApprovalTemplateType.ELEVATOR_LOFTING_PAYMENT,
                                        elevatorDetail = elevatorDetail,
                                        userInfo = userInfo,
                                        onNavigateToApproval = onNavigateToApproval,
                                        onNavigateToApprovalWithTemplate = onNavigateToApprovalWithTemplate
                                    )
                                }
                            )
                        }
                    }
                    
                    // 慢车调试打款按钮 - 在导轨厅门安装到已归档状态之间都显示
                    if (elevatorDetail.status >= Constants.ElevatorStatus.TRACK_DOOR_INSTALLATION && 
                        elevatorDetail.status <= Constants.ElevatorStatus.ARCHIVED) {
                        item {
                            BottomActionButton(
                                icon = Icons.Default.AttachMoney,
                                title = "慢车调试打款",
                                onClick = { 
                                    handleApprovalButtonClick(
                                        templateType = Constants.ApprovalTemplateType.ELEVATOR_SLOW_CAR_DEBUGGING_PAYMENT,
                                        elevatorDetail = elevatorDetail,
                                        userInfo = userInfo,
                                        onNavigateToApproval = onNavigateToApproval,
                                        onNavigateToApprovalWithTemplate = onNavigateToApprovalWithTemplate
                                    )
                                }
                            )
                        }
                    }
                    
                    // 导轨厅门安装打款按钮 - 在快车调试到已归档状态之间都显示
                    if (elevatorDetail.status >= Constants.ElevatorStatus.FAST_CAR_DEBUGGING && 
                        elevatorDetail.status <= Constants.ElevatorStatus.ARCHIVED) {
                        item {
                            BottomActionButton(
                                icon = Icons.Default.Money,
                                title = "导轨厅门安装打款",
                                onClick = { 
                                    handleApprovalButtonClick(
                                        templateType = Constants.ApprovalTemplateType.ELEVATOR_TRACK_DOOR_INSTALLATION_PAYMENT,
                                        elevatorDetail = elevatorDetail,
                                        userInfo = userInfo,
                                        onNavigateToApproval = onNavigateToApproval,
                                        onNavigateToApprovalWithTemplate = onNavigateToApprovalWithTemplate
                                    )
                                }
                            )
                        }
                    }
                    
                    // 快车调试打款按钮 - 在验收到已归档状态之间都显示
                    if (elevatorDetail.status >= Constants.ElevatorStatus.ACCEPTANCE && 
                        elevatorDetail.status <= Constants.ElevatorStatus.ARCHIVED) {
                        item {
                            BottomActionButton(
                                icon = Icons.Default.CreditCard,
                                title = "快车调试打款",
                                onClick = { 
                                    handleApprovalButtonClick(
                                        templateType = Constants.ApprovalTemplateType.ELEVATOR_FAST_CAR_DEBUGGING_PAYMENT,
                                        elevatorDetail = elevatorDetail,
                                        userInfo = userInfo,
                                        onNavigateToApproval = onNavigateToApproval,
                                        onNavigateToApprovalWithTemplate = onNavigateToApprovalWithTemplate
                                    )
                                }
                            )
                        }
                    }
                    
                    // 验收打款按钮 - 在移交到已归档状态之间都显示
                    if (elevatorDetail.status >= Constants.ElevatorStatus.TRANSFER && 
                        elevatorDetail.status <= Constants.ElevatorStatus.ARCHIVED) {
                        item {
                            BottomActionButton(
                                icon = Icons.Default.AccountBalance,
                                title = "验收打款",
                                onClick = { 
                                    handleApprovalButtonClick(
                                        templateType = Constants.ApprovalTemplateType.ELEVATOR_ACCEPTANCE_PAYMENT,
                                        elevatorDetail = elevatorDetail,
                                        userInfo = userInfo,
                                        onNavigateToApproval = onNavigateToApproval,
                                        onNavigateToApprovalWithTemplate = onNavigateToApprovalWithTemplate
                                    )
                                }
                            )
                        }
                    }
                    
                    // 移交打款按钮 - 在待归档到已归档状态之间都显示
                    if (elevatorDetail.status >= Constants.ElevatorStatus.ARCHIVE_PENDING && 
                        elevatorDetail.status <= Constants.ElevatorStatus.ARCHIVED) {
                        item {
                            BottomActionButton(
                                icon = Icons.Default.SwapHoriz,
                                title = "移交打款",
                                onClick = { 
                                    handleApprovalButtonClick(
                                        templateType = Constants.ApprovalTemplateType.ELEVATOR_TRANSFER_PAYMENT,
                                        elevatorDetail = elevatorDetail,
                                        userInfo = userInfo,
                                        onNavigateToApproval = onNavigateToApproval,
                                        onNavigateToApprovalWithTemplate = onNavigateToApprovalWithTemplate
                                    )
                                }
                            )
                        }
                    }
                    
                    // 如果电梯状态为慢车调试，则显示电梯慢车调试按钮
                    if (elevatorDetail.status == Constants.ElevatorStatus.SLOW_CAR_DEBUGGING) {
                        // 电梯慢车调试按钮
                        item {
                            BottomActionButton(
                                icon = Icons.Default.Settings,
                                title = "电梯慢车调试",
                                enabled = elevatorDetail.check_inspection, // 根据check_inspection控制按钮状态
                                onClick = { 
                                    handleApprovalButtonClick(
                                        templateType = Constants.ApprovalTemplateType.ELEVATOR_SLOW_CAR_DEBUGGING,
                                        elevatorDetail = elevatorDetail,
                                        userInfo = userInfo,
                                        onNavigateToApproval = onNavigateToApproval,
                                        onNavigateToApprovalWithTemplate = onNavigateToApprovalWithTemplate
                                    )
                                }
                            )
                        }
                    }
                    
                    // 如果电梯状态为导轨厅门安装，则显示电梯导轨厅门安装按钮
                    if (elevatorDetail.status == Constants.ElevatorStatus.TRACK_DOOR_INSTALLATION) {
                        item {
                            BottomActionButton(
                                icon = Icons.Default.Build,
                                title = "电梯导轨厅门安装",
                                enabled = elevatorDetail.check_inspection, // 根据check_inspection控制按钮状态
                                onClick = { 
                                    handleApprovalButtonClick(
                                        templateType = Constants.ApprovalTemplateType.ELEVATOR_TRACK_DOOR_INSTALLATION,
                                        elevatorDetail = elevatorDetail,
                                        userInfo = userInfo,
                                        onNavigateToApproval = onNavigateToApproval,
                                        onNavigateToApprovalWithTemplate = onNavigateToApprovalWithTemplate
                                    )
                                }
                            )
                        }
                    }
                    
                    // 如果电梯状态为快车调试，则显示电梯快车调试按钮
                    if (elevatorDetail.status == Constants.ElevatorStatus.FAST_CAR_DEBUGGING) {
                        item {
                            BottomActionButton(
                                icon = Icons.Default.Speed,
                                title = "电梯快车调试",
                                onClick = { 
                                    handleApprovalButtonClick(
                                        templateType = Constants.ApprovalTemplateType.ELEVATOR_FAST_CAR_DEBUGGING,
                                        elevatorDetail = elevatorDetail,
                                        userInfo = userInfo,
                                        onNavigateToApproval = onNavigateToApproval,
                                        onNavigateToApprovalWithTemplate = onNavigateToApprovalWithTemplate
                                    )
                                }
                            )
                        }
                    }
                    
                    // 如果电梯状态为验收，则显示电梯验收按钮
                    if (elevatorDetail.status == Constants.ElevatorStatus.ACCEPTANCE) {
                        item {
                            BottomActionButton(
                                icon = Icons.Default.CheckCircle,
                                title = "电梯验收",
                                onClick = { 
                                    handleApprovalButtonClick(
                                        templateType = Constants.ApprovalTemplateType.ELEVATOR_ACCEPTANCE,
                                        elevatorDetail = elevatorDetail,
                                        userInfo = userInfo,
                                        onNavigateToApproval = onNavigateToApproval,
                                        onNavigateToApprovalWithTemplate = onNavigateToApprovalWithTemplate
                                    )
                                }
                            )
                        }
                    }
                    
                    // 如果电梯状态为移交，则显示电梯移交按钮
                    if (elevatorDetail.status == Constants.ElevatorStatus.TRANSFER) {
                        // 检查移交条件：check_overdue = false 且 到货单和开箱确认表都有form_id
                        val arrivalFormId = getFormIdByKey(elevatorDetail.approval_config, Constants.ApprovalTemplateType.getTypeKey(Constants.ApprovalTemplateType.ELEVATOR_ARRIVAL))
                        val unpackingFormId = getFormIdByKey(elevatorDetail.approval_config, Constants.ApprovalTemplateType.getTypeKey(Constants.ApprovalTemplateType.ELEVATOR_UNPACKING))
                        val canTransfer = !elevatorDetail.check_overdue && arrivalFormId != 0 && unpackingFormId != 0
                        
                        item {
                            BottomActionButton(
                                icon = Icons.AutoMirrored.Filled.ExitToApp,
                                title = "电梯移交",
                                enabled = canTransfer, // 根据移交条件控制按钮状态
                                onClick = { 
                                    handleApprovalButtonClick(
                                        templateType = Constants.ApprovalTemplateType.ELEVATOR_TRANSFER,
                                        elevatorDetail = elevatorDetail,
                                        userInfo = userInfo,
                                        onNavigateToApproval = onNavigateToApproval,
                                        onNavigateToApprovalWithTemplate = onNavigateToApprovalWithTemplate
                                    )
                                }
                            )
                        }
                    }
                }
                
                // 如果没有显示任何按钮，显示暂无流程操作提示
                if (elevatorDetail == null || !hasAnyButtons(elevatorDetail)) {
                    item {
                        Box(
                            modifier = Modifier.fillMaxWidth(),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = "暂无流程操作",
                                fontSize = 14.sp,
                                color = Color(0xFF9CA3AF),
                                fontWeight = FontWeight.Medium
                            )
                        }
                    }
                }
            }
        }
    }
}

/**
 * 从 ApprovalConfig 对象中根据 key 获取对应的 form_id (类似 JS 的 obj[key])
 * @param approvalConfig 审批配置对象
 * @param key 小写key
 * @return 对应的 form_id，如果找不到则返回 0
 */
private fun getFormIdByKey(approvalConfig: com.sinogrand.elevator.data.models.ApprovalConfig, key: String): Int {
    return try {
        // 使用反射获取属性值，类似 JS 的 obj[key]
        val field = approvalConfig.javaClass.getDeclaredField(key)
        field.isAccessible = true
        field.getInt(approvalConfig)
    } catch (e: Exception) {
        Log.w(LogTags.ELEVATOR_DETAIL, "⚠️ 无法通过key '$key' 获取form_id: ${e.message}")
        0
    }
}

/**
 * 处理审批按钮点击逻辑
 * @param templateType 审批模版类型枚举
 * @param elevatorDetail 电梯详情信息
 * @param userInfo 用户信息
 * @param onNavigateToApproval 使用form_id跳转的回调
 * @param onNavigateToApprovalWithTemplate 使用template_id跳转的回调
 */
private fun handleApprovalButtonClick(
    templateType: String,
    elevatorDetail: ElevatorDetailInfo,
    userInfo: com.sinogrand.elevator.data.models.UserInfo?,
    onNavigateToApproval: (formId: Int, elevatorId: Int, projectId: Int) -> Unit,
    onNavigateToApprovalWithTemplate: (templateId: Int, elevatorId: Int, projectId: Int) -> Unit
) {
    // 特殊权限检查：电梯防护照片需要 check_inspection 为 true
    if (templateType == Constants.ApprovalTemplateType.ELEVATOR_PROTECTION && !elevatorDetail.check_inspection) {
        Log.w(LogTags.ELEVATOR_DETAIL, "⚠️ 电梯防护照片操作被拒绝 - check_inspection: ${elevatorDetail.check_inspection}")
        return
    }

    // 特殊权限检查：电梯慢车调试需要 check_inspection 为 true
    if (templateType == Constants.ApprovalTemplateType.ELEVATOR_SLOW_CAR_DEBUGGING && !elevatorDetail.check_inspection) {
        Log.w(LogTags.ELEVATOR_DETAIL, "⚠️ 电梯慢车调试操作被拒绝 - check_inspection: ${elevatorDetail.check_inspection}")
        return
    }
    
    // 特殊权限检查：电梯导轨厅门安装需要 check_inspection 为 true
    if (templateType == Constants.ApprovalTemplateType.ELEVATOR_TRACK_DOOR_INSTALLATION && !elevatorDetail.check_inspection) {
        Log.w(LogTags.ELEVATOR_DETAIL, "⚠️ 电梯导轨厅门安装操作被拒绝 - check_inspection: ${elevatorDetail.check_inspection}")
        return
    }
    
    // 特殊权限检查：电梯移交需要满足三个条件
    if (templateType == Constants.ApprovalTemplateType.ELEVATOR_TRANSFER) {
        val arrivalFormId = getFormIdByKey(elevatorDetail.approval_config, Constants.ApprovalTemplateType.getTypeKey(Constants.ApprovalTemplateType.ELEVATOR_ARRIVAL))
        val unpackingFormId = getFormIdByKey(elevatorDetail.approval_config, Constants.ApprovalTemplateType.getTypeKey(Constants.ApprovalTemplateType.ELEVATOR_UNPACKING))
        
        if (elevatorDetail.check_overdue) {
            Log.w(LogTags.ELEVATOR_DETAIL, "⚠️ 电梯移交操作被拒绝 - check_overdue: ${elevatorDetail.check_overdue}")
            return
        }
        if (arrivalFormId == 0) {
            Log.w(LogTags.ELEVATOR_DETAIL, "⚠️ 电梯移交操作被拒绝 - 电梯到货单form_id为0")
            return
        }
        if (unpackingFormId == 0) {
            Log.w(LogTags.ELEVATOR_DETAIL, "⚠️ 电梯移交操作被拒绝 - 电梯开箱确认表form_id为0")
            return
        }
    }
    
    // 获取小写key
    val key = Constants.ApprovalTemplateType.getTypeKey(templateType)
    Log.d(LogTags.ELEVATOR_DETAIL, "🔑 获取到的小写key: $key")
    
    // 从 approval_config 中获取 form_id (类似 JS 的 obj[key])
    val formId = getFormIdByKey(elevatorDetail.approval_config, key)
    
    Log.d(LogTags.ELEVATOR_DETAIL, "📋 从approval_config获取的form_id: $formId")
    
    // 从 userInfo.template_list 中获取 template_id
    val templateId = userInfo?.template_list?.get(templateType) ?: 0
    Log.d(LogTags.ELEVATOR_DETAIL, "📄 从template_list获取的template_id: $templateId")
    
    if (formId != 0) {
        // 如果form_id不为0，说明已经提交过，跳转到查看页面
        Log.d(LogTags.ELEVATOR_DETAIL, "✅ 使用form_id跳转 - formId: $formId, elevatorId: ${elevatorDetail.id}, projectId: ${elevatorDetail.project_id}")
        onNavigateToApproval(formId, elevatorDetail.id, elevatorDetail.project_id)
    } else if (templateId != 0) {
        // 如果form_id为0但template_id不为0，说明没有提交过，使用template_id跳转到创建页面
        Log.d(LogTags.ELEVATOR_DETAIL, "📝 使用template_id跳转 - templateId: $templateId, elevatorId: ${elevatorDetail.id}, projectId: ${elevatorDetail.project_id}")
        onNavigateToApprovalWithTemplate(templateId, elevatorDetail.id, elevatorDetail.project_id)
    } else {
        // 如果两个都为0，说明没有权限或配置错误
        Log.w(LogTags.ELEVATOR_DETAIL, "⚠️ 无法跳转 - formId: $formId, templateId: $templateId, templateType: $templateType")
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ElevatorOverdueExplanationTab(
    elevatorId: Int,
    projectId: Int,
    onNavigateToApproval: (formId: Int, elevatorId: Int, projectId: Int) -> Unit
) {
    // 输出接收到的参数
    Log.d(LogTags.ELEVATOR_DETAIL, "⚠️ ElevatorOverdueExplanationTab 接收参数 - elevatorId: $elevatorId")
    
    val context = LocalContext.current
    val elevatorRepository = remember { ElevatorRepository(context) }
    
    var isRefreshing by rememberSaveable { mutableStateOf(false) }
    var isLoadingMore by rememberSaveable { mutableStateOf(false) }
    var canLoadMore by rememberSaveable { mutableStateOf(true) }
    var currentPage by rememberSaveable { mutableIntStateOf(1) }
    var isLoading by rememberSaveable { mutableStateOf(true) }
    var errorMessage by rememberSaveable { mutableStateOf<String?>(null) }
    
    val pullRefreshState = rememberPullToRefreshState()
    val listState = rememberLazyListState()
    
    // 真实超期说明数据
    var overdueExplanations by rememberSaveable { mutableStateOf<List<ElevatorLogItem>>(emptyList()) }
    
    // 初始化数据
    LaunchedEffect(elevatorId) {
        isLoading = true
        errorMessage = null
        
        elevatorRepository.getElevatorLogList(elevatorId, 3, 1, 20)
            .onSuccess { response: ElevatorLogListResponse ->
                overdueExplanations = response.list
                canLoadMore = response.page_info.page < (response.page_info.total / response.page_info.size + 1)
                isLoading = false
            }
            .onFailure { exception ->
                errorMessage = exception.message
                isLoading = false
            }
    }
    
    // 下拉刷新
    if (pullRefreshState.isRefreshing) {
        LaunchedEffect(true) {
            isRefreshing = true
            elevatorRepository.getElevatorLogList(elevatorId, 3, 1, 20)
                .onSuccess { response: ElevatorLogListResponse ->
                    overdueExplanations = response.list
                    currentPage = 1
                    canLoadMore = response.page_info.page < (response.page_info.total / response.page_info.size + 1)
                }
                .onFailure { exception ->
                    errorMessage = exception.message
                }
            isRefreshing = false
            pullRefreshState.endRefresh()
        }
    }
    
    // 上拉加载更多
    LaunchedEffect(listState) {
        snapshotFlow { listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index }
            .collect { lastVisibleIndex ->
                if (lastVisibleIndex != null && 
                    lastVisibleIndex >= overdueExplanations.size - 1 && 
                    canLoadMore && 
                    !isLoadingMore &&
                    overdueExplanations.isNotEmpty()) { // 确保列表不为空
                    isLoadingMore = true
                    elevatorRepository.getElevatorLogList(elevatorId, 3, currentPage + 1, 20)
                        .onSuccess { response: ElevatorLogListResponse ->
                            overdueExplanations = overdueExplanations + response.list
                            currentPage++
                            canLoadMore = response.page_info.page < (response.page_info.total / response.page_info.size + 1)
                        }
                        .onFailure { exception ->
                            errorMessage = exception.message
                        }
                    isLoadingMore = false
                }
            }
    }
    
    Box(
        modifier = Modifier
            .fillMaxSize()
            .nestedScroll(pullRefreshState.nestedScrollConnection)
    ) {
        when {
            isLoading -> {
                // 加载状态
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator(
                        color = Color(0xFF3B82F6)
                    )
                }
            }
            errorMessage != null -> {
                // 错误状态
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Icon(
                            imageVector = Icons.Default.Error,
                            contentDescription = null,
                            tint = Color(0xFFEF4444),
                            modifier = Modifier.size(64.dp)
                        )
                        
                        Spacer(modifier = Modifier.height(16.dp))
                        
                        Text(
                            text = "加载失败",
                            fontSize = 16.sp,
                            color = Color(0xFF6B7280),
                            fontWeight = FontWeight.Medium
                        )
                        
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        Text(
                            text = errorMessage ?: "未知错误",
                            fontSize = 14.sp,
                            color = Color(0xFF9CA3AF)
                        )
                    }
                }
            }
            overdueExplanations.isEmpty() -> {
                // 空状态 - 使用LazyColumn确保有足够高度触发下拉刷新
                LazyColumn(
                    modifier = Modifier.fillMaxSize(),
                    contentPadding = PaddingValues(16.dp),
                    verticalArrangement = Arrangement.Center
                ) {
                    item {
                        Column(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Icon(
                                imageVector = Icons.Default.Warning,
                                contentDescription = null,
                                tint = Color(0xFF9CA3AF),
                                modifier = Modifier.size(64.dp)
                            )
                            
                            Spacer(modifier = Modifier.height(16.dp))
                            
                            Text(
                                text = "暂无超期说明记录",
                                fontSize = 16.sp,
                                color = Color(0xFF6B7280),
                                fontWeight = FontWeight.Medium
                            )
                            
                            Spacer(modifier = Modifier.height(8.dp))
                            
                            Text(
                                text = "下拉刷新获取最新数据",
                                fontSize = 14.sp,
                                color = Color(0xFF9CA3AF)
                            )
                        }
                    }
                }
            }
            else -> {
                // 超期说明列表
                LazyColumn(
                    state = listState,
                    modifier = Modifier.fillMaxSize(),
                    contentPadding = PaddingValues(16.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    items(overdueExplanations.size) { index ->
                        val explanation = overdueExplanations[index]
                        ElevatorLogItemCard(
                            log = explanation,
                            onClick = { 
                                Log.d(LogTags.ELEVATOR_DETAIL, "⚠️ 超期说明点击 - formId: ${explanation.form_id}, elevatorId: $elevatorId, projectId: $projectId")
                                onNavigateToApproval(explanation.form_id, elevatorId, projectId) 
                            }
                        )
                    }
                
                    // 加载更多指示器
                    if (isLoadingMore) {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(24.dp),
                                    color = Color(0xFF3B82F6),
                                    strokeWidth = 2.dp
                                )
                            }
                        }
                    }
                }
            }
        }
        
        // 下拉刷新容器
        if (pullRefreshState.isRefreshing || pullRefreshState.progress > 0f) {
            PullToRefreshContainer(
                state = pullRefreshState,
                modifier = Modifier
                    .align(Alignment.TopCenter)
                    .zIndex(1f)
            )
        }
    }
}

// 模拟超期说明数据
fun getMockOverdueExplanations(page: Int = 1): List<LogItem> {
    return if (page == 1) {
        listOf(
            LogItem(1, "电梯年检超期说明", "电梯年检已超期15天，需要尽快安排年检工作", "超期", "2025-01-15 09:00:00", 1),
            LogItem(2, "维护保养超期说明", "电梯维护保养已超期7天，影响设备正常运行", "超期", "2025-01-15 14:30:00", 1),
            LogItem(3, "安全检测超期说明", "电梯安全检测已超期30天，存在安全隐患", "超期", "2025-01-16 10:15:00", 1),
            LogItem(4, "配件更换超期说明", "电梯配件更换已超期10天，需要及时处理", "超期", "2025-01-16 16:45:00", 1),
            LogItem(5, "系统升级超期说明", "电梯系统升级已超期20天，影响功能使用", "超期", "2025-01-17 11:20:00", 1)
        )
    } else {
        emptyList() // 模拟没有更多数据
    }
}

@Composable
fun OverdueExplanationCard(explanation: LogItem) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color.White
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 1.dp),
        shape = RoundedCornerShape(8.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = explanation.title,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Medium,
                    color = Color(0xFF1F2937)
                )
                
                Text(
                    text = explanation.created_at,
                    fontSize = 12.sp,
                    color = Color(0xFF9CA3AF)
                )
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            Text(
                text = explanation.content,
                fontSize = 14.sp,
                color = Color(0xFF6B7280),
                lineHeight = 20.sp
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Card(
                    colors = CardDefaults.cardColors(
                        containerColor = Color(0xFFFEF3C7) // 超期说明使用黄色主题
                    ),
                    elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
                    shape = RoundedCornerShape(4.dp)
                ) {
                    Text(
                        text = explanation.type,
                        fontSize = 12.sp,
                        color = Color(0xFFD97706), // 黄色文字
                        modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)
                    )
                }
            }
        }
    }
}
